import { Component, ChangeDetectionStrategy, OnInit, Input, ViewChild } from '@angular/core';
import {
  NzModalRef,
  NzMessageService,
  NzDrawerRef,
  NzFormatEmitEvent,
  NzTreeComponent,
  NzTreeNode,
  NzNotificationService,
} from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { replaceKeysDeep } from '@shared';

@Component({
  selector: 'menu-auth-modal',
  templateUrl: './menu-auth-modal.component.html',
})
export class MenuAuthModalComponent implements OnInit {
  constructor(
    private modal: NzModalRef,
    public http: _HttpClient,
    private msg: NzMessageService,
    private notice: NzNotificationService,
  ) {}
  @Input()
  record: any;
  // 用于菜单的加载
  loading = false;
  // 用于权限的加载
  loading2 = false;
  // 菜单树节点
  nodes = [];
  defaultSelectedKeys = [];
  // 节点树映射
  mapShortToLong = {
    id: 'key',
    name: 'title',
  };
  searchValue = '';
  activedNode: NzTreeNode;

  checkOptionsOne = [];
  indeterminate = false;
  allChecked = false;

  @ViewChild('menuTree', { static: false }) menuTree: NzTreeComponent;
  menuIds = [];

  ngOnInit() {
    this.loadMenuAuths();
  }

  /**
   * 加载全部菜单
   */
  loadMenuAuths() {
    this.loading = true;
    this.http.get(`/cf/admin/menu/tree?type=0`).subscribe(res => {
      if (res.status === 200) {
        this.nodes = [];
        const o: [] = replaceKeysDeep(res.data, this.mapShortToLong);
        o.forEach(r => {
          this.nodes.push(r);
        });
        this.http.get(`/cf/admin/menu/tree/${this.record.roleId}?type=0&notroot=1`).subscribe(res1 => {
          this.defaultSelectedKeys = res1;
        });
      }
      this.loading = false;
    });
  }

  // 递归获取被选中的
  private getChecked(node) {
    if (node.children.length !== 0) {
      for (const child of node.children) {
        this.getChecked(child);
      }
    } else {
      this.menuIds.push(node.origin.key);
    }
  }

  ok() {
    this.menuIds = [];
    this.menuTree.getCheckedNodeList().forEach(r => {
      this.menuIds.push(r.origin.key);
      this.getChecked(r);
    });
    this.menuTree.getHalfCheckedNodeList().forEach(r => {
      this.menuIds.push(r.origin.key);
    });

    this.http
      .put(`/cf/admin/role/menu?roleId=${this.record.roleId}&menuIds=${Array.from(new Set(this.menuIds)).join(',')}`)
      .subscribe(res => {
        if (res.status === 200) {
          this.notice.success('成功', '操作成功');
          this.modal.close();
          this.cancel();
        }
      });
  }

  cancel() {
    this.modal.destroy();
  }

  nzEvent(event: NzFormatEmitEvent): void {
    if (event.eventName === 'click') {
      if (event.node.isSelected) {
        this.loadPermissions(event.node.key);
        this.activedNode = event.node!;
      }
    }
  }

  /**
   * 加载指定菜单下的权限
   */
  loadPermissions(menuId) {
    this.loading2 = true;
    this.checkOptionsOne = [];
    this.indeterminate = false;
    this.allChecked = false;
    this.http.get(`/cf/admin/menu/tree/${this.record.roleId}?type=1&parentId=${menuId}`).subscribe(res1 => {
      const myAuths = res1;
      this.http.get(`/cf/admin/menu/tree?type=1&parentId=${menuId}`).subscribe(res => {
        if (res.status === 200) {
          res.data.forEach(r => {
            this.checkOptionsOne.push({
              label: r.label,
              value: r.id,
              checked: myAuths.indexOf(r.id) > -1 ? true : false,
            });
          });
          this.updateSingleChecked();
        }
        this.loading2 = false;
      });
    });
  }

  updateAllChecked(callApi = false) {
    this.indeterminate = false;
    if (this.allChecked) {
      this.checkOptionsOne = this.checkOptionsOne.map(item => {
        return {
          ...item,
          checked: true,
        };
      });
    } else {
      this.checkOptionsOne = this.checkOptionsOne.map(item => {
        return {
          ...item,
          checked: false,
        };
      });
    }
    // 调用接口更新角色权限
    if (callApi) {
      this.updatePermission();
    }
  }

  updateSingleChecked(callApi = false) {
    if (this.checkOptionsOne.every(item => item.checked === false)) {
      this.allChecked = false;
      this.indeterminate = false;
    } else if (this.checkOptionsOne.every(item => item.checked === true)) {
      this.allChecked = true;
      this.indeterminate = false;
    } else {
      this.indeterminate = true;
    }
    // 调用接口更新角色权限
    if (callApi) {
      this.updatePermission();
    }
  }

  private updatePermission() {
    const permissions = this.checkOptionsOne
      .filter(item => item.checked)
      .map(item => item.value)
      .join(',');

    this.http
      .put(
        `/cf/admin/role/permission?roleId=${this.record.roleId}&menuIds=${permissions}&parentMenuId=${this.activedNode.key}`,
      )
      .subscribe(res => {
        if (res.status === 200) {
          this.notice.success('成功', '操作成功');
        }
      });
  }
}
